package com.czy.owner.ui.wheel;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.adapter.WheelBrandAdapter;
import com.czy.owner.adapter.WheelOtherAttrAdapter;
import com.czy.owner.entity.SpecialGoodsAttrModel;
import com.czy.owner.entity.WheelAttrKeyVal;
import com.czy.owner.entity.WheelAttrModel;
import com.czy.owner.entity.WheelAttrParentModel;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.StatusBarUtil;
import com.czy.owner.widget.MyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Raven on 2018/1/5.
 */

public class WheelAttrFilterLayout extends RelativeLayout {

    private Context mContext;
    private MyRecyclerView brandRecyclerView;//品牌
    private EditText etMinPrice;
    private EditText etMaxPrice;
    private MyRecyclerView otherRecyclerView;//其他类别

    private TextView tvAllBrand;
    private Button btnReset;
    private Button btnOk;
    private LinearLayout llFilterMenuRoot;
    private SpecialGoodsAttrModel majorModel;

    //所有的Brand;
    private List<WheelAttrModel> allBrandList = new ArrayList<>();

    private List<WheelAttrParentModel> attrParentModelList ;

    public WheelAttrFilterLayout(Context context) {
        super(context);
        mContext = context;
        inflateView();
    }

    private void inflateView() {
        View.inflate(getContext(), R.layout.layout_wheel_filter_side, this);

        brandRecyclerView = (MyRecyclerView) findViewById(R.id.recycler_view_brand);
        etMinPrice = (EditText)findViewById(R.id.et_min_price);
        etMaxPrice = (EditText)findViewById(R.id.et_max_price);

        otherRecyclerView = (MyRecyclerView) findViewById(R.id.recycler_view_other_attr);
        tvAllBrand = (TextView) findViewById(R.id.tv_all_brand) ;
        btnReset = (Button) findViewById(R.id.btn_reset);
        llFilterMenuRoot = (LinearLayout) findViewById(R.id.ll_filter_menu_root);
        InputFilter[] filters = {new CashierInputFilter()};
        etMinPrice.setFilters(filters);
        etMaxPrice.setFilters(filters);
//        etMinPrice.addTextChangedListener(new MyTextWatcher(etMinPrice));
//        etMaxPrice.addTextChangedListener(new MyTextWatcher(etMaxPrice));

        btnOk = (Button) findViewById(R.id.btn_ok);
        btnReset.setOnClickListener(mOnClickListener);
        btnOk.setOnClickListener(mOnClickListener);
        tvAllBrand.setOnClickListener(mOnClickListener);
        setRecyclerView();
    }

    private void setRecyclerView(){
        brandRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        otherRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));


        /**品牌*/
        brandAdapter = new WheelBrandAdapter(mContext);
        brandRecyclerView.setAdapter(brandAdapter);

        wheelOtherAttrAdapter = new WheelOtherAttrAdapter(mContext);
        otherRecyclerView.setAdapter(wheelOtherAttrAdapter);

       //品牌栅格布局监听
        brandAdapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object o) {
                Log.d("RAVEN","OnItemClick==" +position);
                brandAdapter.getAllData().get(position).setChoosed(!brandAdapter.getAllData().get(position).isChoosed());
            }
        });



    }

    //品牌列表适配
    private WheelBrandAdapter brandAdapter ;
    //其他类型
    private WheelOtherAttrAdapter wheelOtherAttrAdapter ;

    public boolean isNullData(){
        return majorModel == null;
    }
    public void setData(SpecialGoodsAttrModel model){
        if(model != null) {
            majorModel = model;

            /**处理品牌*/
            allBrandList.clear();
            if(majorModel.getBrandList() != null) {
                for (int i = 0; i < majorModel.getBrandList().size(); ++i) {
                    allBrandList.add(new WheelAttrModel(majorModel.getBrandList().get(i).getGoodsBrandId(), majorModel.getBrandList().get(i).getChName()));
                }
                //Adpater 只添加9项
                for (int i = 0; i < (allBrandList.size() > 9 ? 9 : allBrandList.size()); ++i) {
                    brandAdapter.add(allBrandList.get(i));
                }

                tvAllBrand.setVisibility(allBrandList.size() > 9 ? VISIBLE : GONE);
            }

            attrParentModelList = new ArrayList<>();
            if(model.getAttributesList()!=null) {
                for (int i = 0; i < model.getAttributesList().size(); ++i) {
                    String attrName = model.getAttributesList().get(i).getGoodsAttributesName();
                    if (attrName.equals("胎面宽") || attrName.equals("扁平比") || attrName.equals("直径")) {
                        continue;
                    }
                    attrParentModelList.add(WheelAttrParentModel.transfer(model.getAttributesList().get(i)));
                }

                wheelOtherAttrAdapter.addAll(attrParentModelList);

                wheelOtherAttrAdapter.setOnItemAllClickedListener(new WheelOtherAttrAdapter.OnItemAllClickedListener() {
                    @Override
                    public void onItemAllClicked(int parentPosition) {
                        showOtherAttrPopupWindow(parentPosition);
                    }
                });
            }
        }
    }

    private CloseMenuCallBack menuCallBack;

    public interface CloseMenuCallBack {
        void setupCloseMean(String brandsId , String minPrice, String maxPrice, List<WheelAttrKeyVal> otherAttrs);
    }

    public void setCloseMenuCallBack(CloseMenuCallBack menuCallBack) {
        this.menuCallBack = menuCallBack;
    }


    private OnClickListenerWrapper mOnClickListener = new OnClickListenerWrapper() {
        @Override
        protected void onSingleClick(View v) {
            switch (v.getId()) {
                case R.id.btn_reset:
                    resetData();
                    break;
                case R.id.btn_ok:
                    dealFinalData();
                    break;
                case R.id.tv_all_brand:
                    showAllBrandPopupWindow();
                    break;
            }
        }
    };

    public void resetData(){
        if(allBrandList != null && brandAdapter!= null) {
            for (WheelAttrModel model : allBrandList) {
                model.setChoosed(false);
            }
            brandAdapter.notifyDataSetChanged();
        }
        etMinPrice.setText("");
        etMaxPrice.setText("");
        if(attrParentModelList != null && wheelOtherAttrAdapter != null) {
            for (int i = 0; i < attrParentModelList.size(); ++i) {
                MyLog.d("RAVEN", "名称：" + attrParentModelList.get(i).getName() + "--id = " + attrParentModelList.get(i).getId());
                for (WheelAttrModel model : attrParentModelList.get(i).getAttrModelList()) {
                    model.setChoosed(false);
                }
            }
            wheelOtherAttrAdapter.notifyDataSetChanged();
        }
    }

    /**重新打开页面 重置数据*/
    public void setCopyData(){

        if(copyAllBrandList.size() == allBrandList.size()) {
            for (int i = 0; i < copyAllBrandList.size(); ++i) {
                allBrandList.get(i).setChoosed(copyAllBrandList.get(i).isChoosed());
            }
        }

        if(copyAttrParentModelList.size() == attrParentModelList.size()) {
            for (int i = 0; i < copyAttrParentModelList.size(); ++i) {
                for (int j = 0; j < copyAttrParentModelList.get(i).getAttrModelList().size(); ++j) {
                    attrParentModelList.get(i).getAttrModelList().get(j).setChoosed(copyAttrParentModelList.get(i).getAttrModelList().get(j).isChoosed());
                }
            }
        }

        brandAdapter.notifyDataSetChanged();
        wheelOtherAttrAdapter.notifyDataSetChanged();
        if(copyMaxPrice.equals("999999.99")){
            etMaxPrice.setText("");
        }else {
            etMaxPrice.setText(""+copyMaxPrice);
        }
        if(copyMinPrice.equals("0")){
            etMinPrice.setText("");
        }else {
            etMinPrice.setText("" + copyMinPrice);
        }




    }

    /*这四条作为数据备份，重新打开时重置此页数据*/
    private List<WheelAttrModel> copyAllBrandList = new ArrayList<>();
    private String copyMinPrice = "";
    private String copyMaxPrice = "";
    private List<WheelAttrParentModel> copyAttrParentModelList = new ArrayList<>();

    private void dealFinalData(){
        copyAllBrandList.clear();
        copyAttrParentModelList.clear();
        String brandIds = "";
        /**选中的品牌*/
        List<WheelAttrModel> selectedBrands = new ArrayList<>();
        for(WheelAttrModel model:allBrandList){
            if(model.isChoosed()){
                selectedBrands.add(model);
                MyLog.d("RAVEN","选了"+model.getName()+"  id = " + model.getId());
                brandIds = (brandIds.equals("") ? "" : (brandIds+",")) + model.getId();
            }

            /**拷贝品牌*/
            copyAllBrandList.add(new WheelAttrModel(model.getId(),model.getName(),model.isChoosed()));
        }



        /**价格区间*/
        String minPrice = etMinPrice.getText().toString();
        String maxPrice = etMaxPrice.getText().toString();
        if(TextUtils.isEmpty(minPrice) ){
            minPrice = "0";
        }

        if(TextUtils.isEmpty(maxPrice)){
            maxPrice = "999999.99";
        }

        try {
            if(Float.parseFloat(minPrice) > Float.parseFloat(maxPrice)){
                PhoneUtils.ShowToastMessage(mContext,"价格区间不合法");
                return;
            }
        }catch (NumberFormatException e){

        }

        /**拷贝价格*/
        copyMinPrice = ""+minPrice;
        copyMaxPrice = ""+maxPrice;


        /**其他的选择*/

        List<WheelAttrKeyVal> wheelAttrKeyValList = new ArrayList<>();

        for(int i = 0 ; i < attrParentModelList.size();++i){
            MyLog.d("RAVEN","名称："+attrParentModelList.get(i).getName()+"--id = " + attrParentModelList.get(i).getId());
            WheelAttrKeyVal attrKeyVal = new WheelAttrKeyVal(attrParentModelList.get(i).getId(),"");//父级id保存
            String attrValStr = "";

            List<WheelAttrModel> tmpWheelAttrModels = new ArrayList<>();
            copyAttrParentModelList.add(new WheelAttrParentModel(attrParentModelList.get(i).getId(),attrParentModelList.get(i).getName(),tmpWheelAttrModels));

            for(WheelAttrModel model:attrParentModelList.get(i).getAttrModelList()){
                if(model.isChoosed()){
                    MyLog.d("RAVEN","选了"+model.getName()+"  id = " + model.getId());
                    attrValStr = (attrValStr.equals ("") ? "":(attrValStr+",")) + model.getName();
                }
                tmpWheelAttrModels.add(new WheelAttrModel(model.getId(),model.getName(),model.isChoosed()));
            }
            if(!TextUtils.isEmpty(attrValStr)) {
                attrKeyVal.setAttrVal(attrValStr);
                wheelAttrKeyValList.add(attrKeyVal);
            }

        }


        //品牌属性结果
        MyLog.d("RAVEN","==========最终结果=======");
        MyLog.d("RAVEN","==========>BrandIds="+brandIds);
        MyLog.d("RAVEN","最小价格："+minPrice);
        MyLog.d("RAVEN","最大价格："+maxPrice);
        MyLog.d("RAVEN","==========>otherAttrs = " +wheelAttrKeyValList.toString());

        menuCallBack.setupCloseMean(brandIds, minPrice,maxPrice,wheelAttrKeyValList);
    }






    /***********************************其他的筛选Pop*******************************************/

    private PopupWindow mOtherAttrPop;
    public WheelFilterChildMenuLayout mOtherAttrLayout;
    protected void showOtherAttrPopupWindow(int position) {
        hintKb();
        final List<WheelAttrModel> attrChildModelList = attrParentModelList.get(position).getAttrModelList();
        /**拷贝一份数据传过去  主要清除选中标记*/
        List<WheelAttrModel> copyList = new ArrayList<>();
        for(WheelAttrModel model:attrChildModelList){
            copyList.add(new WheelAttrModel(model));
        }

        mOtherAttrLayout = new WheelFilterChildMenuLayout(getContext(),attrChildModelList,copyList);
        if (mOtherAttrPop == null) {
            mOtherAttrPop = new PopupWindow(mOtherAttrLayout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        }
        mOtherAttrPop.setBackgroundDrawable(new BitmapDrawable());
        mOtherAttrPop.setAnimationStyle(R.style.popupWindowAnimRight);
        mOtherAttrPop.setFocusable(true);
        mOtherAttrPop.showAtLocation(WheelAttrFilterLayout.this, Gravity.TOP, 100, StatusBarUtil.getStatusBarHeight(mContext));
        mOtherAttrPop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                dismissMenuPop();
            }
        });

        mOtherAttrLayout.setOnBtnClickedListener(new WheelFilterChildMenuLayout.OnBtnClickedListener() {
            @Override
            public void onCancel() {
                dismissMenuPop();
            }

            @Override
            public void onEnsure(List<WheelAttrModel> optAttrs) {

                /**optAttrs，在所有分类操作后的数据*/
                for(int i = 0 ; i < optAttrs.size();++i){
//                    MyLog.d("RAVEN","optAttrs name = " + optAttrs.get(i).getName() + "===isChoosed = " + optAttrs.get(i).isChoosed() + "==id = "+
//                            optAttrs.get(i).getId());
                    for(int j = 0; j < attrChildModelList.size();++j){

                        if(optAttrs.get(i).getId() == attrChildModelList.get(j).getId()){
                            attrChildModelList.get(j).setChoosed(optAttrs.get(i).isChoosed());
                        }
                    }

                }
                wheelOtherAttrAdapter.notifyDataSetChanged();
                dismissMenuPop();
            }
        });
    }

    /***********************************全部品牌*******************************************/
    private void hintKb() {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() &&  ((Activity)mContext).getCurrentFocus() != null) {
            if (((Activity)mContext).getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(((Activity)mContext).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 创建所有品牌PopupWindow
     */
    private PopupWindow mAllBrandPop;
    public WheelFilterChildMenuLayout mAllBrandMenuLayout;

    protected void showAllBrandPopupWindow() {
        hintKb();
        /**拷贝一份数据传过去  主要清除选中标记*/
        List<WheelAttrModel> copyBrandList = new ArrayList<>();
        for(WheelAttrModel model:allBrandList){
            copyBrandList.add(new WheelAttrModel(model));
        }
        mAllBrandMenuLayout = new WheelFilterChildMenuLayout(getContext(),allBrandList,copyBrandList);
        if (mAllBrandPop == null) {
            mAllBrandPop = new PopupWindow(mAllBrandMenuLayout, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        }
        mAllBrandPop.setBackgroundDrawable(new BitmapDrawable());
        mAllBrandPop.setAnimationStyle(R.style.popupWindowAnimRight);
        mAllBrandPop.setFocusable(true);
        mAllBrandPop.showAtLocation(WheelAttrFilterLayout.this, Gravity.TOP, 100, StatusBarUtil.getStatusBarHeight(mContext));
        mAllBrandPop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                dismissMenuPop();
            }
        });
        mAllBrandMenuLayout.setOnBtnClickedListener(new WheelFilterChildMenuLayout.OnBtnClickedListener() {
            @Override
            public void onCancel() {
                dismissMenuPop();
            }

            @Override
            public void onEnsure(List<WheelAttrModel> optAttrs) {
                /**optAttrs，在所有品牌分类操作后的数据*/
                for(int i = 0 ; i < optAttrs.size();++i){
                    for(int j = 0; j < allBrandList.size();++j){
                        if(optAttrs.get(i).getId() == allBrandList.get(j).getId()){
                            allBrandList.get(j).setChoosed(optAttrs.get(i).isChoosed());
                        }
                    }

                }
                brandAdapter.notifyDataSetChanged();
                dismissMenuPop();
            }
        });
    }

    public boolean childViewIsShowing(){
        if(mAllBrandPop != null && mAllBrandPop.isShowing()){
            return true;
        }

        if(mOtherAttrPop != null && mOtherAttrPop.isShowing()){
            return true;
        }
        return false;
    }

    /**
     * 关闭窗口
     */
    public void dismissMenuPop() {
        if (mAllBrandPop != null) {
            mAllBrandPop.dismiss();
            mAllBrandPop = null;
        }

        if(mOtherAttrPop != null){
            mOtherAttrPop.dismiss();
            mOtherAttrPop = null;
        }
    }

    /**带两位小数的价格输入监听*/
    class MyTextWatcher implements TextWatcher {

        private EditText editText;
        public MyTextWatcher(EditText editText) {
            this.editText = editText;
        }

        private boolean isChanged = false;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            MyLog.d("RAVEN","--->"+s);
            if(!TextUtils.isEmpty(s.toString())) {
                if (isChanged) {// ----->如果字符未改变则返回
                    return;
                }
                String str = s.toString();

                isChanged = true;
                String cuttedStr = str;
                /* 删除字符串中的dot */
                for (int i = str.length() - 1; i >= 0; i--) {
                    char c = str.charAt(i);
                    if ('.' == c) {
                        cuttedStr = str.substring(0, i) + str.substring(i + 1);
                        break;
                    }
                }
                /* 删除前面多余的0 */
                int NUM = cuttedStr.length();
                int zeroIndex = -1;
                for (int i = 0; i < NUM - 2; i++) {
                    char c = cuttedStr.charAt(i);
                    if (c != '0') {
                        zeroIndex = i;
                        break;
                    } else if (i == NUM - 3) {
                        zeroIndex = i;
                        break;
                    }
                }
                if (zeroIndex != -1) {
                    cuttedStr = cuttedStr.substring(zeroIndex);
                }
                /* 不足3位补0 */
                if (cuttedStr.length() < 3) {
                    cuttedStr = "0" + cuttedStr;
                }
                /* 加上dot，以显示小数点后两位 */
                cuttedStr = cuttedStr.substring(0, cuttedStr.length() - 2)
                        + "." + cuttedStr.substring(cuttedStr.length() - 2);

                editText.setText(cuttedStr);
                editText.setSelection(editText.length());
                isChanged = false;
            }
        }
    }
}
